import axios from "axios";
import Vue from "vue";
import { getAutoToken } from "@/common/localStoreToken";
const vm = new Vue();
// 通用数据配置
const axiosServe1 = axios.create({
  baseURL: "/api",
  timeout: 5000,
});
const axiosServe2 = axios.create({
  timeout: 5000,
});
const other = ["/user/login", "/user/validate/code", "/user/app/login","/prologue",'/']; //白名单
// 添加请求拦截器
axiosServe1.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    if (other.includes(config.url)) return config; //对白名单放行
    let token = vm.$myStore.getters["common/token"];
      //  let token = getAutoToken()
    console.log('xxxxxxxxxxx');

    if (!token) Promise.reject(400, "token认证失败,请重新登录"); //如果token就中断请求}
    config.headers["token"] = token; //将token添加到请求头中
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosServe1.interceptors.response.use((response) => {
  // 对响应数据做点什么
  let { data } = response;
  if (
    data.code === 403 &&
    data.message === "Request information authentication failed."
  ) {
    alert("用户登录失效，请重新登录");
    vm.$router.push("/login");
  } else {
    return response;
  }
});
// 基于Promise
/**
 * 封装的axios异步请求方法
 * @param {{url: string, method: 'get' | 'post' | 'delete' | 'put', data: any, params: any}} req 请求对象
 * @return Promise
 */
export const ajax = (req) => {
  if (!req || !req.url) throw new TypeError("url地址必传");
  return new Promise((resolve) => {
    axiosServe1({
      url: req.url,
      // 默认为post
      method: req.method || "get",
      params: req.params || {},
      data: req.data || {},
    })
      .then(({ data }) => {

        resolve(data);
      })
      .catch(({ code, message }) => {
        resolve({ code, message });
      });
  });
};
export const ajax2 = (req) => {
  if (!req || !req.url) throw new TypeError("url地址必传");
  return new Promise((resolve) => {
    axiosServe2({
      url: req.url,
      // 默认为post
      method: req.method || "get",
      params: req.params || {},
      data: req.data || {},
    })
      .then(({ data }) => {

        resolve(data);
      })
      .catch(({ code, message }) => {
        resolve({ code, message });
      });
  });
};
